/*全局方法文件*/
/*引入实例化后的vue对象*/
import vm from '../main'

/*引入axios*/
import axios from 'axios'
/*引入vuex*/
import store from '../store'
/*引入吐司*/
import {Toast} from "vant";
/*引入解密*/
import CryptoJS from '../../static/lib/crypto-js.min.js'
// import 'vant/lib/button/style';
/*请求地址*/
const requestUrl = {
    /*开发地址*/
    dev: 'https://www.371zhongyi.com',
    // dev:'http://192.168.6.150:7001',
    /*测试地址*/
    test: '',
    /*正式地址*/
    formal: 'https://www.371zhongyi.com'
};
/*公共信息*/
const publicInfo = {
    /*公共aes解密图片秘钥*/
    aesKey: "46cc793c53dc451b",
    logoUrl: require('../assets/logo.png'),
    /*正则表达式*/
    regList: {
        /*email: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,*/
        email:/@/,
        phone: /^1[3-9]\d{9}$/
    },
    /*可选头像数组*/
    userIconList: [
        {
            id: 0,
            url: require('../assets/defaultUserIcon.png')
        },
        {
            id: 1,
            url: require('../assets/userIcon/1.png')
        },
        {
            id: 2,
            url: require('../assets/userIcon/2.png')
        },
        {
            id: 3,
            url: require('../assets/userIcon/3.png')
        },
        {
            id: 4,
            url: require('../assets/userIcon/4.png')
        },
        {
            id: 5,
            url: require('../assets/userIcon/5.png')
        },
        {
            id: 6,
            url: require('../assets/userIcon/6.png')
        },
        {
            id: 7,
            url: require('../assets/userIcon/7.png')
        },
        {
            id: 8,
            url: require('../assets/userIcon/8.png')
        },
        {
            id: 9,
            url: require('../assets/userIcon/9.png')
        },
        {
            id: 10,
            url: require('../assets/userIcon/10.png')
        },
        {
            id: 11,
            url: require('../assets/userIcon/11.png')
        },
        {
            id: 12,
            url: require('../assets/userIcon/12.png')
        },
        {
            id: 13,
            url: require('../assets/userIcon/13.png')
        },
        {
            id: 14,
            url: require('../assets/userIcon/14.png')
        },
        {
            id: 15,
            url: require('../assets/userIcon/15.png')
        },
        {
            id: 16,
            url: require('../assets/userIcon/16.png')
        },
        {
            id: 17,
            url: require('../assets/userIcon/17.png')
        },
        {
            id: 18,
            url: require('../assets/userIcon/18.png')
        },
        {
            id: 19,
            url: require('../assets/userIcon/19.png')
        },
        {
            id: 20,
            url: require('../assets/userIcon/20.png')
        }
    ],
};
/*公共方法*/
const globalFunctions = {
    /*字符加密*/
    encryptRequest(word) {
        /*公共秘钥，这边先写死*/
        let key = CryptoJS.enc.Utf8.parse(publicInfo.aesKey);
        let srcs = CryptoJS.enc.Utf8.parse(word);
        let encrypted = CryptoJS.AES.encrypt(srcs, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        return encrypted.toString();
    },
    /*解密方法*/
    decryptRequest(word) {
        /*公共秘钥，这边先写死*/
        let key = CryptoJS.enc.Utf8.parse(publicInfo.aesKey);
        let decrypt = CryptoJS.AES.decrypt(word, key, {
            /*以下两个属性需要和加密对应*/
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        return CryptoJS.enc.Utf8.stringify(decrypt).toString();
    },
    /*回到顶部*/
    backTop() {
        var timer = setInterval(function () {
            let osTop = document.documentElement.scrollTop || document.body.scrollTop;
            let ispeed = Math.floor(-osTop / 5);
            document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed;
            this.isTop = true;
            if (osTop === 0) {
                clearInterval(timer);
            }
        }, 30)
    },
    /*返回placeholder*/
    returnPublicPlaceholder() {
        if (store.state.configInfo === null) {
            return "";
        }
        return store.state.configInfo.searchPlaceHolder;
    },
    /*返回时间*/
    getDateDiff(minutesTimeStamp) {
        if (!minutesTimeStamp || minutesTimeStamp < 0) {
            return '';
        }
        if (minutesTimeStamp <= 60) {
            return `${minutesTimeStamp}分钟前`;
        }
        let hours = minutesTimeStamp / 60; //小时
        if (hours <= 24) { //今天
            return `${parseInt(hours)}小时前`;
        }
        if (hours > 24 && hours <= 24 * 30) { //这个月
            let day = hours / 24;
            return `${parseInt(day)}天前`;
        }
        if (hours > 24 * 30 && hours <= 24 * 30 * 365) { //大于一个月 小于一年
            let month = hours / (24 * 30);
            return `${parseInt(month)}月前`;
        }
        if (hours > 24 * 30 * 365) { //大于1年
            let year = hours / (24 * 30 * 365);
            return `${parseInt(year)}年前`;
        }
        return `${minutesTimeStamp}分钟前`;
    },
    /*生成随机标识码*/
    getSignCode() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    },
    /*生成组合随机标识码*/
    getSignCodeStr() {
        return (globalFunctions.getSignCode() + globalFunctions.getSignCode() + "-" + globalFunctions.getSignCode() + "-" + globalFunctions.getSignCode() + "-" + globalFunctions.getSignCode() + "-" + globalFunctions.getSignCode() + globalFunctions.getSignCode() + globalFunctions.getSignCode());
    },
    /*解密方法*/
    decryptAESFn(word) {
        /*公共秘钥，这边先写死*/
        let key = CryptoJS.enc.Utf8.parse(publicInfo.aesKey);
        let decrypt = CryptoJS.AES.decrypt(word, key, {
            /*以下两个属性需要和加密对应*/
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        return CryptoJS.enc.Utf8.stringify(decrypt).toString();
    },
    /*把url解析成对象*/
    parseQueryString(url=window.location.href) {
        let json = {};
        let arr = url.substr(url.indexOf('?') + 1).split('&');
        arr.forEach((item)=>{
            let tmp = item.split('=');
            json[tmp[0]] = tmp[1];
        });
        console.log('打印解析出的对象');
        console.log(json);
        return json.id;
    },
    /*取得当前获取的代理id的方法*/
    getAgentIDFn() {
        /*先执行测试是否有id，没有的话，直接返回null*/
        if(globalFunctions.parseQueryString()===undefined) return null;
        if (window.location.href.indexOf('?') === -1) return null;
        /*如果不存在id且本地存储也没有agentId，那么直接返回null*/
        if (window.location.href.split('?').length === 1 && store.state.agentId === null) return null;
        /*如果当前代理id已经存储且当前id和解析网址的id一样，那么直接返回那个id*/
        //if (store.state.agentId !== null && (store.state.agentId == globalFunctions.parseQueryString())) return store.state.agentId;
        /*console.log(window.location.href.split('?'));*/
        /*如果存在id且和当前解析网址id不一样，那么进行以下逻辑*/
        return globalFunctions.parseQueryString();
    },
    /*当前是否绑定邮箱或者手机号*/
    isBindingAccount() {
        if (store.state.isLogin === false) {
            /*console.log('没登录呀');*/
            return "";
        }
        if ((store.state.userInfo.email === "" || store.state.userInfo.email === null) && (store.state.userInfo.phone === "" || store.state.userInfo.phone === null)) {
            /*console.log('没有绑定账号');*/
            return false;
        }
        /* console.log('已经绑定账号');*/
        return true;
    },
    /*公用的返回头像的方法*/
    publicReturnUserIcon(id) {
        if (id === 0) {
            return publicInfo.userIconList[0].url;
        }
        for (let obj of publicInfo.userIconList) {
            if (obj.id === id) {
                return obj.url
            }
        }
    },
    //获取随机的名字
    randWord(count = 1, type, len = 10) {
        // const rand = 'ABCDEFGJIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        // const rand2 = '1234567890abcdefghijklmnopqrstuvwxyz';
        // const rand3 = '1234567890';
        let o = '';
        const text = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGJIJKLMNOPQRSTUVWXYZ';
        const rdmIndex = text => Math.random() * text.length | 0;
        let rdmString = '';
        for (; rdmString.length < len; rdmString += text.charAt(rdmIndex(text))) {
            ;
        }
        return rdmString + this.getTimeString().substr(0, 12);
    },
    /*公共返回热度数字的方法*/
    returnHotTextFn(num) {
        if (num < 10000) {
            return num;
        }
        return parseInt(num / 10000) + Number((num % 10000 / 10000).toFixed(1)) + '万'
        /*return `${}${(num%10000/10000).toFixed(1)}万`;*/
    },
    /*获取标准日期*/
    getFormatData(ms) {
        let time = new Date(ms);
        return time.getFullYear() + '.' + (time.getMonth() + 1) + '.' + time.getDate() + '过期';
    },
    /*获取时间字符串方法*/
    getTimeString() {
        let date = new Date(),
            Y = date.getFullYear(),
            M = date.getMonth(),
            D = date.getDate(),
            h = date.getHours(),
            m = date.getMinutes(),
            s = date.getSeconds(),
            time = Y.toString() + M.toString() + D.toString() + h.toString() + m.toString() + s.toString();
        let math = Math.random() * 1000000000000000000;
        return time + math.toString();
    },

    /*取得视频时长的方法*/
    getVideoTimeLength(s) {
        let hours = null;
        let minutes = null;
        let second = 0;
        /*处理小时，大于等于1赋值(取整)，否则为0*/
        (s / 3600) >= 1 ? hours = Math.floor(s / 3600) : hours = 0;
        /*处理分钟，如果hours有值，那么直接用总分钟数-hours*60，就是需要的值*/
        if (hours === 0) {
            minutes = Math.floor(s / 60);
        } else if (hours > 0) {
            minutes = Math.floor(s / 60 - hours * 60);
        }
        /*处理秒前的0数值*/
        if (minutes < 10) {
            minutes = '0' + minutes;
        }
        /*处理秒，总秒数-之前已经显示的秒数，就是剩下的秒数*/
        if (s < 60) {
            /*如果秒数小于60，那么直接秒数直接为当前参数的秒数*/
            second = s;
        } else if (s === 60) {
            s = 0;
        } else if (s > 60) {
            /*如果秒数大于60，那么减去之前小时和分钟占用的秒数，就是剩下的秒数*/
            second = s - (hours * 60 * 60 + minutes * 60);
        }
        /*处理秒前的0数值*/
        if (second < 10) {
            second = '0' + second;
        }
        /*返回显示*/
        if (hours === 0) {
            return `${minutes}:${second}`;
        } else {
            return `${hours}:${minutes}:${second}`;
        }
        /*if (minutes.toString().length === 1) {
            minutes = "0" + minutes;
        }
        //秒
        if (second.toString().length === 1) {
            second = "0" + second;
        }*/
    },
    /*验证是否登录*/
    userIsLogin() {
        return store.state.isLogin;
        /*if(vm.$store.state.isLogin===true){
            return true;
        }
        return true;*/
    },
    /*验证token是否过期*/
    isTokenExpired() {

    },
    /*返回充值地址*/
    returnRechargeURL(rechargeType) {
        if (store.state.isLogin === true) {
            // return "http://192.168.6.161:8365/#/"+"?token="+store.state.userInfo.token;
            return store.state.configInfo.pointPay + "?token=" + store.state.userInfo.token + "&type=" + rechargeType;
        }
        // return "http://192.168.6.161:8365/#/";
        return store.state.configInfo.pointPay + "?type=" + rechargeType;
    },
    /*返回客服地址*/
    returnCustomerServiceUrl() {
        if (store.state.isLogin === true) {
            // return store.state.configInfo.customerAdvisory.split('=')[0] + "=" + store.state.userInfo.userId;
            return store.state.configInfo.customerAdvisory.replace(/{uid}/g,store.state.userInfo.userId);
        }
        return store.state.configInfo.customerAdvisory;
    },
    /*返回加盟地址*/
    returnAgentLoginUrl() {
        // return "http://agent.cxbj168.cn/#/?token="+store.state.userInfo.token;
        if (store.state.isLogin === true) {
            return store.state.configInfo.agentLogin + "?token=" + store.state.userInfo.token;
        }
        return store.state.configInfo.agentLogin;
    },
    /*公共打开某一网页的地址*/
    publicOpenNewWindow(url) {
        let newTab = window.open('about:blank');
        newTab.location.href = url;
        newTab = null;
    },
    /*判断是否是什么平台的设备*/
    returnDevicePlatform(){
        if(/Win/i.test(navigator.platform)){
            return "Windows";
        }
        if(/Mac/i.test(navigator.platform)){
            // document.write("这是Mac操作系统平台");
            return "Mac";
        }
        if(/Linux/i.test(navigator.platform)){
            // document.write("这是Linux操作系统平台（包括安卓系统）");
            return "Linux";
        }
        if(/iOS/i.test(navigator.platform)) {
            // document.write("这是iOS操作系统平台");
            return "Ios";
        }
    },
    /*返回当前需要使用的url的方法*/
    returnNowApiBaseUrl() {
        switch (store.state.mode) {
            case 0:
                return requestUrl.dev;
            case 1:
                return requestUrl.test;
            case 2:
                return requestUrl.formal;
            default:
                return requestUrl.dev;
        }
    },
    /*查询当前是什么端*/
    whichClientIs() {
        /*返回参数:1 windows 5 Android 4 iphone*/
        let u = navigator.userAgent;
        if (u.match(/android/ig) || u.match(/Linux/ig)) {
            // console.log('安卓端');
            /*u = null;*/
            /*Toast('安卓端');*/
            return 5;
        } else if (u.match(/iphone|ipod|iOS/ig) || u.match(/ipad/ig)) {
            // console.log('苹果端');
            /*u = null;*/
            /*Toast('苹果端');*/
            return 4;
        } else if (u.indexOf('Windows') > -1) {
            // console.log('pc端');
            /*u = null;*/
            /*Toast('pc端');*/
            return 1;
        } else if (/Mac/i.test(navigator.platform)) {
            /*mac端*/
            return 1;
        }
        /*alert('打印客户端类型');
        alert(u)*/
    },
    /*计算列表总页数*/
    totalPageCountFn(size, total) {
        //计算结果
        if (total === 0) {
            return 1;
        }
        let pageTotal = parseInt(total) / parseInt(size);
        if (pageTotal <= 1) {
            //如果小于1，就只有一页
            return 1;
        } else if (pageTotal > 1 && (parseInt(pageTotal) == pageTotal) === false) {
            //当前计算结果大于1且是小数，那么返回page+1
            return parseInt(pageTotal) + 1;
        } else if (pageTotal > 1 && (parseInt(pageTotal) == pageTotal) === true) {
            //当前计算结果大于1且是整数，那么返回page
            return parseInt(pageTotal);
        }
    },
    /*通用的跳转videoContent的方法*/
    publicLinkToVideoContent(id) {
        this.$router.push({name: 'linkPage', id: id});
    },
    /*根据不同端，跳不同页面*/
    returnDeviceShouldVisit() {
        if (globalFunctions.whichClientIs() === 1) {
            if (globalFunctions.getAgentIDFn() !== null) {
                console.log('打印跳转网址');
                alert(store.state.configInfo.pcWebUrl + "?id=" + globalFunctions.getAgentIDFn());
                // window.location.href=store.state.configInfo.pcWebUrl+"?id="+globalFunctions.getAgentIDFn();
                return;
            }
            /*直接打开pc页面*/
            /*window.location.href = store.state.configInfo.pcWebUrl;*/
        }
    },
    /*获取历史记录时间方法*/
    getTimeStringForHistory() {
        let date = new Date(),
            Y = date.getFullYear(),
            M = date.getMonth(),
            D = date.getDate(),
            h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
            m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
            s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(),
            time = `${Y.toString()}-${M.toString()}-${D.toString()}  ${h.toString()}:${m.toString()}:${s.toString()}`;
        return time;
    },
    /*公共的添加历史记录的方法*/
    addVideoHistory(video, oldHistoryList) {
        /*
        * video:当前添加的video对象，格式如下
        * obj={
            videoId:123,
            name:"哦牛批视频",
            active:false,
            needVip:false,
            addTime:"2020年10月1日 20:46:03",
            coverImgUrl:""
        }
        * oldHistoryList:当前的历史记录数组(不可超过30条，如果超过30条，那么替换第一个)
        * */
        /*深拷贝一份*/
        let historyList = JSON.parse(JSON.stringify(oldHistoryList));
        /*先判断是否有相同id的元素，如果有，那么立即删除*/
        for (let obj of historyList) {
            if (obj.videoId === video.videoId) {
                historyList.splice(historyList.indexOf(obj), 1);
                break;
            }
        }
        /*先判断是否超过30个*/
        if (historyList.length >= 30) {
            /*如果超过30个，那么删除最后一个，并且在首位添加*/
            historyList.pop();
            historyList.unshift(video);
            /*使用vuex方法重新赋值*/
            store.commit('changeVideoHistory', historyList);
            historyList = null;
            return true;
        }
        /*没有超过，那么查找是否直接unshift并赋值*/
        historyList.unshift(video);
        store.commit('changeVideoHistory', historyList);
        historyList = null;
        return true;
    },
    /*公共的删除历史记录的方法*/
    delVideoHistory(videoIdList, oldHistoryList) {
        /*
        * index:当前元素下标
        * oldHistoryList:当前的历史记录数组(不可超过30条，如果超过30条，那么替换第一个)
        * */
        /*深拷贝一份*/
        let historyList = JSON.parse(JSON.stringify(oldHistoryList));
        /*循环删除对应的下标*/
        for (let id of videoIdList) {
            for (let obj of historyList) {
                if (obj.videoId === id) {
                    /*删除对应下标的元素*/
                    historyList.splice(historyList.indexOf(obj), 1);
                }
            }

        }

        /*使用vuex方法重新赋值*/
        store.commit('changeVideoHistory', historyList);
        historyList = null;
        return true;
    }
};

export default {
    globalFunctions,
    publicInfo
}



// WEBPACK FOOTER //
// ./src/global/globalTools.js